import React, { useState } from 'react';
import { Card, Switch, Select, Button, Space, Divider, Tabs, App } from 'antd';
import { useTheme } from '../contexts/ThemeContext';
import { themes } from '../config/themes';
import type { ThemeId } from '../types/theme';
import ColorPreview from '../components/ColorPreview';

const Settings: React.FC = () => {
  const { theme, themeId, setTheme } = useTheme();
  const [activeTab, setActiveTab] = useState('general');
  const { message } = App.useApp();

  const handleThemeChange = (newThemeId: ThemeId) => {
    setTheme(newThemeId);
    message.success(`已切换到${themes.find(t => t.id === newThemeId)?.name}主题`);
  };

  const handleClearCache = () => {
    localStorage.removeItem('current-user');
    localStorage.removeItem('users');
    message.success('缓存已清除');
  };

  const handleExportData = () => {
    const data = {
      users: JSON.parse(localStorage.getItem('users') || '[]'),
      currentUser: JSON.parse(localStorage.getItem('current-user') || 'null'),
      theme: themeId,
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `backup-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('数据导出成功');
  };

  const tabItems = [
    {
      key: 'general',
      label: '常规设置',
      children: (
        <div className="space-y-6">
        {/* 外观设置 */}
        <Card title="外观设置">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">主题选择</div>
                <div className="text-sm text-gray-500">选择您喜欢的主题颜色</div>
              </div>
              <Select
                value={themeId}
                onChange={handleThemeChange}
                style={{ width: 200 }}
                options={themes.map(t => ({
                  label: (
                    <div className="flex items-center gap-2">
                      <div className="flex gap-1">
                        <div 
                          className="w-3 h-3 rounded-full border border-gray-200"
                          style={{ backgroundColor: t.colors.primary[500] }}
                        />
                        <div 
                          className="w-3 h-3 rounded-full border border-gray-200"
                          style={{ backgroundColor: t.colors.secondary[500] }}
                        />
                      </div>
                      <span>{t.name}</span>
                    </div>
                  ),
                  value: t.id,
                }))}
              />
            </div>

            <Divider />

            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">深色模式</div>
                <div className="text-sm text-gray-500">自动跟随系统设置</div>
              </div>
              <Switch defaultChecked={false} disabled />
            </div>

            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">动画效果</div>
                <div className="text-sm text-gray-500">启用界面过渡动画</div>
              </div>
              <Switch defaultChecked={true} />
            </div>
          </div>
        </Card>

        {/* 通知设置 */}
        <Card title="通知设置">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">桌面通知</div>
                <div className="text-sm text-gray-500">允许显示桌面通知</div>
              </div>
              <Switch defaultChecked={true} />
            </div>

            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">声音提醒</div>
                <div className="text-sm text-gray-500">新消息时播放提示音</div>
              </div>
              <Switch defaultChecked={false} />
            </div>

            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">邮件通知</div>
                <div className="text-sm text-gray-500">重要事件邮件提醒</div>
              </div>
              <Switch defaultChecked={true} />
            </div>
          </div>
        </Card>

        {/* 数据管理 */}
        <Card title="数据管理">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium">自动保存</div>
                <div className="text-sm text-gray-500">自动保存表单数据</div>
              </div>
              <Switch defaultChecked={true} />
            </div>

            <Divider />

            <div className="space-y-3">
              <div className="font-medium">数据操作</div>
              <Space>
                <Button onClick={handleExportData}>
                  导出数据
                </Button>
                <Button>
                  导入数据
                </Button>
                <Button danger onClick={handleClearCache}>
                  清除缓存
                </Button>
              </Space>
            </div>
          </div>
        </Card>

        {/* 系统信息 */}
        <Card title="系统信息">
          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span>应用版本:</span>
              <span>v1.0.0</span>
            </div>
            <div className="flex justify-between">
              <span>构建时间:</span>
              <span>{new Date().toLocaleDateString()}</span>
            </div>
            <div className="flex justify-between">
              <span>当前主题:</span>
              <span>{theme.name}</span>
            </div>
            <div className="flex justify-between">
              <span>浏览器:</span>
              <span>{navigator.userAgent.split(' ')[0]}</span>
            </div>
          </div>
        </Card>
        </div>
      )
    },
    {
      key: 'colors',
      label: '颜色预览',
      children: <ColorPreview />
    }
  ];

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-800 dark:text-white">系统设置</h1>
        <p className="text-gray-600 dark:text-gray-300 mt-2">个性化您的应用体验</p>
      </div>

      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="large"
      />
    </div>
  );
};

export default Settings;